﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using coffeeshop.Models;
using coffeeshop.AppCore;

namespace coffeeshop.Forms
{
    public partial class frmListTables : Form
    {
        private System.Resources.ResourceManager mv_Resources = new System.Resources.ResourceManager("coffeeshop.Properties.Resources", System.Reflection.Assembly.GetExecutingAssembly());
        private WorkTime _workTime;

        private bool _codeWorkTimeChanged;

        public string ThuNgan { get { return cboThuNgan.Text; } }
        public string CaLam { get { return cboTime.Text; } }
        public frmListTables()
        {
            InitializeComponent();

            LoadCaLamViec(Global.CaLamViec.None);
            LoadThuNgan();
            LoadListTables();

            LoadCaHienTai();
        }

        private void LoadCaHienTai()
        {
            _workTime = WorkTime.GetCaLamViecCuoi();
            // restore trang thai cua ca da chon truoc do ma chua giao ca.
            // neu dang co ca thi hien thi ca 
            if (_workTime.WorkTimeId > 0)
            {
                if (_workTime.IsFinished)
                {
                    LoadCaLamViec(_workTime.PeriodType);
                }
                else
                { 
                    Global.CaLamViec caCuoi = (Global.CaLamViec)Enum.Parse(typeof(Global.CaLamViec), ((int)_workTime.PeriodType - 1).ToString());
                    LoadCaLamViec(caCuoi);
                    //lock ca
                    cboThuNgan.SelectedValue = _workTime.UserId;
                    _codeWorkTimeChanged = true;
                    cboTime.SelectedValue = (int)_workTime.PeriodType;

                    cboThuNgan.Enabled = false;
                    cboTime.Enabled = false;
                }
            }
            else
            {
                // else load blank
                cboThuNgan.SelectedIndex = 0;
                cboTime.Enabled = false;
            }
        }

        private void LoadThuNgan()
        {
            coffeeDataSet.UserDataTable thuNganList = User.GetThuNgan();
            DataRow firstRow = thuNganList.NewRow();
            firstRow["Name"] = string.Empty;
            firstRow["UserId"] = 0;
            firstRow["IsActive"] = false;
            firstRow["UserRoleId"] = 0;
            thuNganList.Rows.InsertAt(firstRow, 0);
            cboThuNgan.DataSource = thuNganList;
            cboThuNgan.DisplayMember = "Name";
            cboThuNgan.ValueMember = "UserId";
        }

        private void LoadCaLamViec(Global.CaLamViec caCuoiCung)
        {
            Array _list;
            if (caCuoiCung == Global.CaLamViec.None)
            {
                _list = new[] { 
                    new { Name = string.Empty, Id = (int)Global.CaLamViec.None }, 
                    new { Name = "S", Id = (int)Global.CaLamViec.CaSang }, 
                    new { Name = "T", Id = (int)Global.CaLamViec.CaTrua },
                    new { Name = "C", Id = (int)Global.CaLamViec.CaChieu }};
            }
            else if (caCuoiCung == Global.CaLamViec.CaSang)
            {
                _list = new[] { 
                new { Name = string.Empty, Id = (int)Global.CaLamViec.None }, 
                new { Name = "T", Id = (int)Global.CaLamViec.CaTrua },
                new { Name = "C", Id = (int)Global.CaLamViec.CaChieu }};
            }
            else if (caCuoiCung == Global.CaLamViec.CaTrua)
            {
                _list = new[] { 
                new { Name = string.Empty, Id = (int)Global.CaLamViec.None }, 
                new { Name = "C", Id = (int)Global.CaLamViec.CaChieu }};
            }
            else
            {
                _list = new[] { 
                new { Name = string.Empty, Id = (int)Global.CaLamViec.None } };
            }

            cboTime.DataSource = _list;
            cboTime.DisplayMember = "Name";
            cboTime.ValueMember = "Id";
        }

        private void LoadListTables()
        {
            String strButtonNameFormat = "btnTable", strLabelNameFormat = "lblTable";
            String strButtonName = "", strLabelName = "", strTblTemp = "";
            int intNumOfRows = 0, intSizeXGroupbox = 0, intSizeYGroupbox = 0;

            try
            {
                coffeeDataSet.OrderTableDataTable objOrderTableData = new coffeeDataSet.OrderTableDataTable();
                objOrderTableData = OrderTable.CountActiveTable();
                // Find num of displayed rows
                intNumOfRows = objOrderTableData.Count / Global.NumOfRowTable;
                if (objOrderTableData.Count % Global.NumOfRowTable > 0)
                {
                    intNumOfRows = intNumOfRows + 1;
                }

                for (int i = 0; i < intNumOfRows; i++)
                {
                    for (int k = 0; k < Global.NumOfRowTable & ((i * Global.NumOfRowTable + k) < objOrderTableData.Count); k++)
                    {
                        strTblTemp = (string)objOrderTableData.Rows[i * Global.NumOfRowTable + k]["Name"].ToString();
                        strButtonName = strButtonNameFormat + strTblTemp;
                        strLabelName = strLabelNameFormat + strTblTemp;

                        //Create buttonEx to show Coffee Table.
                        AppCore.ButtonEx btnObx = new AppCore.ButtonEx();
                        btnObx.Click += orderTable_Click;
                        btnObx.Name = strButtonName;
                        btnObx.Tag = (int)objOrderTableData.Rows[i * Global.NumOfRowTable + k]["OrderTableId"];                        
                        btnObx.Location = new System.Drawing.Point(10 + k * 55, i * 80 + 40 );
                        btnObx.TabIndex = i * Global.NumOfRowTable + k + 10;
                        btnObx.Status = (Global.TableStatus)objOrderTableData.Rows[i * Global.NumOfRowTable + k]["Status"];
                        btnObx.isVisible = true;
                        btnObx.resetButton();
                        grbListTable.Controls.Add(btnObx);

                        //Create label to show name of Coffee Table
                        Label lblObx = new Label();
                        lblObx.Name = strLabelName;
                        lblObx.Text = strTblTemp;
                        lblObx.AutoSize = true;
                        lblObx.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        lblObx.Location = new System.Drawing.Point(25 + k * 55, i * 80 + 20);
                        lblObx.Size = new System.Drawing.Size(24, 16);
                        lblObx.ForeColor = System.Drawing.Color.DarkGreen;
                        grbListTable.Controls.Add(lblObx);

                        // Size of groupbox 
                        if (intSizeXGroupbox < 80 + k * 55 )
                        {
                            intSizeXGroupbox = 80 + k * 55;
                        }
                        if (intSizeYGroupbox < i * 80 + 100)
                        {
                            intSizeYGroupbox = i * 80 + 110;
                        }
                    }                   
                }
                grbListTable.Size = new System.Drawing.Size(intSizeXGroupbox, intSizeYGroupbox);
                grbDesc.Location = new System.Drawing.Point(10, intSizeYGroupbox + 40);
                grbDesc.Size = new System.Drawing.Size(intSizeXGroupbox - 200, 120);
                btnTransfer.Location = new System.Drawing.Point(intSizeXGroupbox - 120, intSizeYGroupbox + 60);
                this.Size = new System.Drawing.Size(intSizeXGroupbox + 35, intSizeYGroupbox + 210);   

                this.lblAvailable.Text = mv_Resources.GetString("TABLEAVAILABLE");
                this.lblServicing.Text = mv_Resources.GetString("TABLESERVICING");
                this.lblBilled.Text = mv_Resources.GetString("TABLEBILLED");
                this.lblChanged.Text = mv_Resources.GetString("TABLECHANGED");
            }
            catch (Exception ex)
            {
                
                MessageBox.Show(ex.Message);
            }            
        }

        private void orderTable_Click(object sender, EventArgs e)
        {
            // kiem tra da nhan ca chua.
            if (cboTime.SelectedIndex == 0)
            {
                MessageBox.Show("Bạn cần phải nhận ca trước khi order");
                return;
            }

            ButtonEx btnTableOrder = (ButtonEx)sender;            
            string objTag = btnTableOrder.Tag.ToString().Trim();
            OrderTable objOrderTable = new OrderTable(Convert.ToInt16(objTag));

            if (btnTableOrder.Status == Global.TableStatus.Available)
            {
                frmOrderDetail frmNew = new frmOrderDetail(objOrderTable, _workTime.WorkTimeId, Global.OrderType.OrderNew);
                frmNew.MyParentForm = this;
                frmNew.StartPosition = FormStartPosition.CenterScreen;
                frmNew.ShowDialog();
                btnTableOrder.Status = frmNew.objOrderTable.Status;
                btnTableOrder.resetButton();
            }
            else
            {
                frmOrderCurrentTable frmNew = new frmOrderCurrentTable(objOrderTable, _workTime.WorkTimeId);
                frmNew.MyParentForm = this;
                frmNew.StartPosition = FormStartPosition.CenterScreen;
                frmNew.ShowDialog();
            }
        }

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.F5)
            {
                frmLoginForm _form = new frmLoginForm();
                _form.StartPosition = FormStartPosition.CenterScreen;
                _form.ShowDialog(this);
                return true;
            }
            if (keyData == Keys.F3)
            {                
                this.txtFindTable.Focus();
                return true;
            }
            if (keyData == Keys.F1)
            {
                this.btnTransfer.Focus();
                frmLoginForm _form = new frmLoginForm();
                _form.StartPosition = FormStartPosition.CenterScreen;
                _form.Show();
                return true;
            }

            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void txtFindTable_Validating(object sender, CancelEventArgs e)
        {
            string strButtonName = "btnTable";            
            try
            {
                if (txtFindTable.Text.ToString().Trim().Length > 0)
                {
                    strButtonName = strButtonName + txtFindTable.Text.ToString().Trim().PadLeft(2, '0');
                    foreach (var v_ctr in grbListTable.Controls)
                    {
                        if (v_ctr.GetType().Name == "ButtonEx")
                        {
                            AppCore.ButtonEx obj = (AppCore.ButtonEx)v_ctr;
                            if (obj.Name == strButtonName)
                            {
                                obj.Focus();
                                break;
                            }
                        }

                    }
                }
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void txtFindTable_Enter(object sender, EventArgs e)
        {
            txtFindTable.SelectAll();
        }

        private void cboThuNgan_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((ComboBox)sender).SelectedIndex == 0)
            {
                cboTime.SelectedIndex = 0;
                cboTime.Enabled = false;
                return;
            }

            cboTime.Enabled = true;
        }

        private void cboTime_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (((ComboBox)sender).SelectedIndex == 0)
                return;

            if (_codeWorkTimeChanged)
            {
                _codeWorkTimeChanged = false;
                return;
            }

            // xac nhan la "nhan ca"
            DialogResult msResult = MessageBox.Show(string.Format("Thu ngân {0} có muốn nhận ca {1} này không?", cboThuNgan.Text, cboTime.Text), 
                "Chú ý", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Question);
            if (msResult == DialogResult.Yes)
            {
                // tao record va khoa control lai
                _workTime = new WorkTime();
                _workTime.UserId = (int)cboThuNgan.SelectedValue;
                _workTime.PeriodType = (Global.CaLamViec)Enum.Parse(typeof(Global.CaLamViec), cboTime.SelectedValue.ToString());
                _workTime.ForDate = DateTime.Now;

                if (_workTime.Save())
                {
                    cboThuNgan.Enabled = false;
                    cboTime.Enabled = false;
                }
                else
                {
                    MessageBox.Show("Có lỗi khi lưu ca làm việc");
                }
            }
            else
            {
                cboTime.SelectedIndex = 0;
            }
        }

        private void btnTransfer_Click(object sender, EventArgs e)
        {
            // validate truoc neu co ca dang nhan
            if (cboTime.SelectedIndex == 0)
            {
                MessageBox.Show("Bạn cần phải nhận ca trước khi giao ca");
                return;
            }

            //TODO: implement the form to "finish a worktime"
            DialogResult _dialog = MessageBox.Show(string.Format("Bạn có chắc là thu ngân {0} muốn giao ca {1} này không?", cboThuNgan.Text, cboTime.Text), 
                "Chú ý", 
                MessageBoxButtons.YesNo, 
                MessageBoxIcon.Question);
            if (_dialog == DialogResult.Yes)
            {
                if (_workTime.SetFinish())
                {
                    // show list product which was selled in this workingtime.
                    frmTransferWorkingtime TranferWorkingTime = new frmTransferWorkingtime(_workTime);
                    TranferWorkingTime.StartPosition = FormStartPosition.CenterParent;
                    TranferWorkingTime.MyParentForm = this;
                    TranferWorkingTime.ShowDialog(this);
                    cboThuNgan.Enabled = true;
                    cboTime.Enabled = false;

                    cboThuNgan.SelectedIndex = 0;
                    cboTime.SelectedIndex = 0;

                    // Ko cho phep chon ca cu.
                    LoadCaLamViec(_workTime.PeriodType);
                }
            }
        }        
    }
}
